package com.example.openAI.openai.ai;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.example.openAI.Util;
import com.example.openAI.openai.ai.param.AiParam;
import com.example.openAI.openai.ai.res.AiRes;
import com.example.openAI.openai.ai.res.XhRes;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.crypto.Data;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class AiUtil {

    private static final String EMBEDDING_URL = "https://api.openai.com/v1/embeddings";
    private static final String XH_EMBEDDING_URL = "http://knowledge-retrieval.cn-huabei-1.xf-yun.com/v1/aiui/embedding/query";
    private static final String AI_KEY = "Bearer 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";
    private static final String AI_MODEL = "text-embedding-ada-002";
    private static final String XH_APP_ID = "5099cb98";
    private static final String XH_APP_KEY = "50443b524d2c7c4268038328cba67d6a";
    private static final String XH_APP_SECRET = "MmVjMGZmYmZjNjcwYjE0MzQ4ZmIzNDIy";

    public static AiRes embedding(String content) {
        AiParam param = new AiParam();
        param.setModel(AI_MODEL);
        param.setInput(content);
        HttpRequest post = HttpRequest.post(EMBEDDING_URL);
        post.contentType("application/json");
        post.header("Authorization", AI_KEY);
        post.body(JSONUtil.toJsonStr(param));
        post.setHttpProxy("127.0.0.1", 7078);
        HttpResponse response = post.execute();
        return JSONUtil.toBean(response.body(), AiRes.class);
    }

    public static XhRes xhEmbedding() {
        //构建url
        String host = "host: " + "knowledge-retrieval.cn-huabei-1.xf-yun.com";
        String date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).format(new Date());
        String path = "POST " + "/v1/aiui/embedding/query" + " HTTP/1.1";
        return null;
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) {
        try {
            URL url = new URL(hostUrl);
            // 时间
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = format.format(new Date());
            // 拼接
            String preStr = "host: " + url.getHost() + "\n" +
                    "date: " + date + "\n" +
                    "POST " + url.getPath() + " HTTP/1.1";
            // System.err.println(preStr);
            // SHA256加密
            Mac mac = Mac.getInstance("hmacsha256");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
            mac.init(spec);

            byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
            // Base64加密
            String sha = Base64.getEncoder().encodeToString(hexDigits);
            // System.err.println(sha);
            // 拼接
            String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
            // 拼接地址
            HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                    addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                    addQueryParameter("date", date).//
                    addQueryParameter("host", url.getHost()).//
                    build();
            // System.err.println(httpUrl.toString());
            return httpUrl.toString();
            //return httpUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        } catch (Exception e) {
            return "";
        }
    }

    public static void main(String[] args) {
        String url = getAuthUrl(XH_EMBEDDING_URL, XH_APP_KEY, XH_APP_SECRET);
        System.out.println(url);
        HttpRequest post = HttpRequest.post(url);
        post.header("app_id", XH_APP_ID);
        post.body("payload", "'text':'text'");
        HttpResponse response = post.execute();
        System.out.println(response.body());
    }

}
